package com.sttg.csp.common.util;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public final class DBUtil {

	private static String driverClass;
	
	private static String url;

	private static String username = "root";

	private static String password = "abcd1234";
	
	private static Properties prop = new Properties();
	
	static {
		try {
			// read configure file config.properties
			InputStream in = LDAPUtil.class.getClassLoader().getResourceAsStream("config.properties");
			prop.load(in);
			
			driverClass = (String) prop.get("jdbc.driverClassName");
			url = (String) prop.get("jdbc.url");
			username = (String) prop.get("jdbc.username");
			password = (String) prop.get("jdbc.password");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	public static Connection getConnection() {
		Connection conn = null;
		try {
			Class.forName(driverClass);
			conn = DriverManager.getConnection(url, username, password);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;

	}

	public static void close(ResultSet rs, Statement stmt, Connection conn) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (stmt != null) {
			try {
				stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

	}

	public static void main(String[] args) {
		Connection con = null;
		Statement stmt = null;
		ResultSet rs = null;
		try {
			con = DBUtil.getConnection();
			System.out.println("Connection successful.");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(rs, stmt, con);
		}
	}
}